package com.xiaoxin.yixinai.userinfo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xiaoxin.yixinai._frame.base.BaseRepository;
import com.xiaoxin.yixinai._frame.base.BaseServiceProxy;
import com.xiaoxin.yixinai._frame.base.Constant;

@Service
@Transactional
public class UserInfoService extends BaseServiceProxy<UserInfo> {
	
	@Resource
	private EntityManager em;

	@Resource
	private UserInfoRepository userInfoRepository;
	
	@Override
	protected BaseRepository<UserInfo> getBaseRepository() {
		return userInfoRepository;
	}
	
	public UserInfo findByLoginName(String loginName){
    	UserInfo userInfo = userInfoRepository.findByLoginNameAndIsDelete(loginName,Constant.NOT_DELETED);
    	return userInfo;
    }

	/**
	 * 查询这个公司的管理员
	 * @param companyId
	 * @return
	 */
	@Transactional(readOnly=true)
	public UserInfo findManagerByCompanyId(Integer companyId) {
		return userInfoRepository.findTop1ByCompanyIdAndIsDeleteOrderByUserIdAsc(companyId,0);
	}
	
	/**
	 * 通过邀请码查询用户（前提是邀请码唯一）
	 * @param myInviterCode
	 * @return
	 */
	@Transactional(readOnly=true)
	public UserInfo findByMyInviterCode(String myInviterCode) {
		return userInfoRepository.findByMyInviterCodeAndIsDelete(myInviterCode, 0);
	}
	
	/**
	 * 查询这些公司的管理员
	 * @param companyIds
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true)
	public List<UserInfo> findManagerByCompanyIdIn(Collection<Integer> companyIds) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT company_id as companyId, MIN(user_id) as userId ");
		sql.append("FROM tb_user_info ");
		sql.append("WHERE is_delete = 0 and company_id in (:companyIds) ");
		sql.append("GROUP BY company_id ");
		Query query = em.createNativeQuery(sql.toString());
		query.setParameter("companyIds", companyIds);
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(UserInfo.class));
		List<UserInfo> list = query.getResultList();
		// 有些公司的管理员被删除了以后，这个方法下面的部分就要出错了，页面就会显示500。至少不让页面显示500吧，所以这里判断一下。
		if (list == null || list.isEmpty()) {
			return null;
		}
		
		Set<Integer> userIds = list.stream().map(c->c.getUserId()).collect(Collectors.toSet());
		
		String hql = "from UserInfo where userId in (:userIds) ";
		Query hqlQuery = em.createQuery(hql);
		hqlQuery.setParameter("userIds", userIds);
		return hqlQuery.getResultList();
	}
	
	/**
	 * 验证 登录名是否重复
	 * @param userId 主键
	 * @param loginName  登录名
	 * @return
	 */
	@Transactional(readOnly=true)
	public UserInfo verifyLoginNameUnique(Integer userId, String loginName) {
		StringBuffer hql = new StringBuffer();
		hql.append("FROM UserInfo WHERE isDelete = :isDelete AND loginName = :loginName ");
		if (userId != null) {
			hql.append("AND userId != :userId ");
		}
		Query query = em.createQuery(hql.toString());
		query.setParameter("isDelete", Constant.NOT_DELETED);
		query.setParameter("loginName", loginName);
		if (userId != null) {
			query.setParameter("userId", userId);
		}
		query.setMaxResults(1);
		UserInfo userInfo = null;
		try {
			userInfo =(UserInfo) query.getSingleResult();
		} catch (NoResultException nre) {
			
		}
		return userInfo;
	}
	
}
